<template>
  <div class="login-container">
    <div class="animated-background">
      <div class="circle"></div>
      <div class="circle"></div>
      <div class="circle"></div>
      <div class="circle"></div>
      <div class="circle"></div>
    </div>

    <div class="login-box">
      <!-- 标题区域 -->
      <div
          class="login-title"
          :class="{
          'slide-left': loginType === 'code' && !isMobile,
          'mobile-title': isMobile
        }"
      >
        <h2>后台管理系统</h2>
        <p>Vue3 + Element Plus + Vite</p>
      </div>
      <!-- 左侧卡片 -->
      <div
        class="login-card left-card"
        :class="{
          'slide-left': loginType === 'code' && !isMobile,
          'active': loginType === 'account'
        }"
      >
        <!-- 账号密码登录表单 -->
        <div class="form-content">
          <h3>账号密码登录</h3>
          <el-form
            ref="accountFormRef"
            :model="accountForm"
            :rules="accountRules"
            @keyup.enter="handleAccountLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="accountForm.username"
                placeholder="用户名"
                :prefix-icon="User"
                clearable
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="accountForm.password"
                type="password"
                placeholder="密码"
                :prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>

            <el-form-item>
              <div class="remember-forgot">
                <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                <el-button type="text" @click="forgotPassword">忘记密码？</el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                :loading="loading"
                @click="handleAccountLogin"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>
          <div class="switch-tip">
            <span>没有账号？</span>
            <a @click="loginType = 'code'">使用验证码登录</a>
          </div>
        </div>
      </div>

      <!-- 右侧卡片 -->
      <div
        class="login-card right-card"
        :class="{
          'slide-left': loginType === 'code' && !isMobile,
          'active': loginType === 'code'
        }"
      >
        <!-- 验证码登录表单 -->
        <div class="form-content">
          <h3>验证码登录</h3>
          <el-form
            ref="codeFormRef"
            :model="codeForm"
            :rules="codeRules"
            @keyup.enter="handleCodeLogin"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="codeForm.phone"
                placeholder="手机号"
                :prefix-icon="Phone"
                clearable
              />
            </el-form-item>

            <el-form-item prop="code">
              <div class="code-input">
                <el-input
                  v-model="codeForm.code"
                  placeholder="验证码"
                  :prefix-icon="Key"
                  maxlength="6"
                  :input-style="{ letterSpacing: '4px' }"
                  clearable
                />
                <el-button
                  type="primary"
                  :disabled="!!timer"
                  @click="sendCode"
                >
                  {{ timer ? `${countdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                :loading="loading"
                @click="handleCodeLogin"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>
          <div class="switch-tip">
            <span>返回</span>
            <a @click="loginType = 'account'">账号密码登录</a>
          </div>
        </div>
      </div>


    </div>

    <div class="login-tips">
      <p>默认账号：admin / 123456</p>
      <p>测试手机号：13800138000</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone, Key, Message } from '@element-plus/icons-vue'
import settings from '@/config/settings'

const router = useRouter()
const loading = ref(false)
const rememberMe = ref(false)
const loginType = ref('account')
const accountFormRef = ref(null)
const codeFormRef = ref(null)
const timer = ref(null)
const countdown = ref(0)

// 添加移动端判断
const isMobile = ref(false)

// 检测设备类型
const checkDevice = () => {
  isMobile.value = window.innerWidth <= 768
}

// 监听窗口大小变化
onMounted(() => {
  checkDevice()
  window.addEventListener('resize', checkDevice)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkDevice)
})

// 监听登录类型变化
watch(loginType, (newType) => {
  if (isMobile.value) {
    // 移动端切换时重置表单
    if (newType === 'account') {
      accountFormRef.value?.resetFields()
    } else {
      codeFormRef.value?.resetFields()
    }
  }
})

// 账号密码登录表单
const accountForm = reactive({
  username: '',
  password: ''
})

const accountRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名不能少于3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于6个字符', trigger: 'blur' }
  ]
}

// 验证码登录表单
const codeForm = reactive({
  phone: '',
  code: ''
})

const codeRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 切换动画样式
const sliderStyle = computed(() => ({
  transform: loginType.value === 'account' ? 'translateX(0)' : 'translateX(100%)'
}))

// 监听登录类型变化，处理移动端显示
watch(loginType, (newType) => {
  const accountCard = document.querySelector('.left-card')
  const codeCard = document.querySelector('.right-card')

  if (newType === 'account') {
    accountCard?.classList.add('active')
    codeCard?.classList.remove('active')
  } else {
    accountCard?.classList.remove('active')
    codeCard?.classList.add('active')
  }
})

// 账号密码登录
const handleAccountLogin = async () => {
  if (!accountFormRef.value) return

  try {
    await accountFormRef.value.validate()
    loading.value = true

    // 模拟登录请求
    setTimeout(() => {
      if (accountForm.username === 'admin' && accountForm.password === '123456') {
        localStorage.setItem('token', 'mock-token')
        ElMessage.success('登录成功')
        router.push('/dashboard')
      } else {
        ElMessage.error('用户名或密码错误')
      }
      loading.value = false
    }, 1000)
  } catch (error) {
    console.error('登录失败:', error)
  }
}

// 验证码登录
const handleCodeLogin = async () => {
  if (!codeFormRef.value) return

  try {
    await codeFormRef.value.validate()
    loading.value = true

    // 模拟登录请求
    setTimeout(() => {
      if (codeForm.phone === '13800138000' && codeForm.code === '123456') {
        localStorage.setItem('token', 'mock-token')
        ElMessage.success('登录成功')
        router.push('/dashboard')
      } else {
        ElMessage.error('手机号或验证码错误')
      }
      loading.value = false
    }, 1000)
  } catch (error) {
    console.error('登录失败:', error)
  }
}

// 发送验证码
const sendCode = async () => {
  if (!codeForm.phone) {
    ElMessage.warning('请输入手机号')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(codeForm.phone)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }

  // 开始倒计时
  countdown.value = 60
  timer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)

  ElMessage.success('验证码已发送')
}

const forgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}

// 切换登录方式
const switchLoginType = (type) => {
  loginType.value = type
  // 重置表单
  if (type === 'account') {
    accountFormRef.value?.resetFields()
  } else {
    codeFormRef.value?.resetFields()
  }
  // 重置加载状态
  loading.value = false
  // 清除倒计时
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
    countdown.value = 0
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to bottom right, #50a3a2 0%, #53e3a6 100%);
  overflow: hidden;
  position: relative;
}

.login-box {
  width: 900px;
  height: 500px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  position: relative;
  display: flex;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  overflow: hidden;
}

.login-card {
  position: absolute;
  width: 50%;
  height: 100%;
  padding: 40px;
  display: flex;
  flex-direction: column;
  transition: transform 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
  background: #fff;
}

.left-card {
  left: 0;
  transform-origin: left center;
}

.right-card {
  right: -50%;
  transform-origin: right center;
}

.slide-left {
  transform: translateX(-100%);
}

.login-title {
  position: absolute;
  width: 50%;
  height: 100%;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: linear-gradient(45deg, #50a3a2 0%, #53e3a6 100%);
  color: #fff;
  transition: transform 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .login-box {
    width: 90%;
    max-width: 400px;
    height: auto;
    min-height: 500px;
    flex-direction: column;
    padding: 20px;
  }

  .login-card {
    position: relative;
    width: 100%;
    height: auto;
    padding: 20px;
    right: auto;
    left: auto;
    display: none;
    transform: none !important;
  }

  .login-card.active {
    display: block;
    animation: fadeIn 0.3s ease forwards;
  }

  .login-title {
    position: relative;
    width: 100%;
    height: auto;
    padding: 20px;
    right: auto;
    transform: none !important;
    margin-bottom: 20px;
    border-radius: 10px;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
}

/* 动画背景 */
.animated-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: -1;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 20s infinite;
}

.circle:nth-child(1) {
  width: 200px;
  height: 200px;
  top: 20%;
  left: 15%;
  animation-delay: 0s;
}

.circle:nth-child(2) {
  width: 300px;
  height: 300px;
  top: 50%;
  left: 70%;
  animation-delay: 5s;
}

.circle:nth-child(3) {
  width: 150px;
  height: 150px;
  top: 80%;
  left: 30%;
  animation-delay: 10s;
}

.circle:nth-child(4) {
  width: 250px;
  height: 250px;
  top: 10%;
  left: 80%;
  animation-delay: 15s;
}

.circle:nth-child(5) {
  width: 100px;
  height: 100px;
  top: 60%;
  left: 10%;
  animation-delay: 20s;
}

@keyframes float {
  0% {
    transform: translateY(0) scale(1);
  }
  50% {
    transform: translateY(-20px) scale(1.1);
  }
  100% {
    transform: translateY(0) scale(1);
  }
}

.form-content {
  width: 100%;
  padding: 40px;
  opacity: 1;
  transition: opacity 0.3s;
}

h2.fade-in, p.fade-in {
  opacity: 0;
  transform: translateY(20px);
  animation: fadeIn 1s forwards;
}

h2.fade-in {
  animation-delay: 0.5s;
}

p.fade-in {
  animation-delay: 1s;
}

@keyframes fadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

.login-title h2 {
  font-size: 32px;
  margin-bottom: 20px;
  font-weight: 600;
}

.login-title p {
  font-size: 16px;
  opacity: 0.8;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  height: 42px;
  background: #f8f9fa;
  box-shadow: none;
  border: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform, box-shadow;
}

:deep(.el-input__wrapper:hover),
:deep(.el-input__wrapper.is-focus) {
  border-color: var(--el-color-primary);
  background: #fff;
}

/* 验证码按钮 */
.code-input {
  display: flex;
  gap: 12px;
}

.code-input .el-input {
  flex: 1;
}

.code-input .el-button {
  width: 120px;
  border-radius: 8px;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 42px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  margin-top: 10px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform, box-shadow;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 记住密码和忘记密码 */
.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

/* 切换提示 */
.switch-tip {
  margin-top: auto;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.switch-tip a {
  color: var(--el-color-primary);
  cursor: pointer;
  margin-left: 5px;
  text-decoration: none;
}

.switch-tip a:hover {
  color: var(--el-color-primary-light-3);
}

/* 提示信息 */
.login-tips {
  margin-top: 20px;
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 13px;
  line-height: 1.8;
}

/* 确保表单内容始终可见 */
.login-card.slide-left .form-content,
.login-card:not(.slide-left) .form-content {
  opacity: 1;
  visibility: visible;
}

/* 动画优化 */
.login-card {
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
}

:deep(.el-form-item__content) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
  box-shadow: none;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover),
:deep(.el-input__wrapper.is-focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 1px var(--el-color-primary);
}
</style>
